package com.cloudkinto.service.statistics.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.common.DateFormater;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.statistics.NotificationService;
import com.cloudkinto.service.statistics.vo.*;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhangyy
 * @since 2020-06-19
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class NotificationServiceImpl extends ServiceImpl<NotificationDao, NotificationDo> implements NotificationService {
    @Autowired
    private NotificationDao dao;
    @Autowired
    private OrderOutputDao orderOutputDao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private StorageDao storageDao;


    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public void add(NotificationAddReq req, Long userId) {
        NotificationDo entityDo = new NotificationDo();
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setCreateTime(new Date());
        entityDo.setCreateBy(userId);
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(NotificationDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }


    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success(detail(id));
    }

    @Override
    public void update(NotificationUpdateReq req, Long userId) {
        NotificationDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(NotificationDo entityDo, Long userId) {
//        entityDo.setUpdateBy(userId);
//        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(NotificationDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
//        NotificationDo entityDo = dao.selectById(id);
//        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(NotificationDo entityDo, Long userId) {
//        entityDo.setDeleteBy(userId);
//        entityDo.setDeleteTime(new Date());
    }

    @Override
    public NotificationDetailRes detail(Long id) {
        NotificationDo entityDo = dao.selectById(id);
        NotificationDetailRes res = new NotificationDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<NotificationPageRes> getList(Map<String, String> map) {
        QueryWrapper<NotificationDo> wrapper = queryBuild(map);
        List<NotificationDo> list = this.list(wrapper);
        List<NotificationPageRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public SingleResult orderOutNotificationList(String type) {
        Map result = new HashMap();

        //当前时间推前1天的12点之前的订单
        Date dateBefore = TimeUtils.parseDate(TimeUtils.getCurrentDateFormat(-1) + " 12:00:00", "yyyy-MM-dd HH:mm:ss");
        Date dateSevenBefore = DateUtils.passingDate(new Date(), -15);

        LambdaQueryWrapper<OrderOutputDo> hasCheckWrapper = new LambdaQueryWrapper<>();
        hasCheckWrapper.le(OrderOutputDo::getStatus, DicBusinessItemConstant.outWaitSendOut)
                .lt(OrderOutputDo::getCreateTime, dateBefore)
                .gt(OrderOutputDo::getCreateTime, dateSevenBefore)
//                .eq(OrderOutputDo::getOrderType, 1)
                .ne(OrderOutputDo::getCompanyId, 30L);
        if ("0".equals(type)) {
            hasCheckWrapper.last("limit 50");
        }
        LambdaQueryWrapper<OrderOutputDo> hasSendOutWrapper = new LambdaQueryWrapper<>();
        hasSendOutWrapper.eq(OrderOutputDo::getStatus, DicBusinessItemConstant.outSendOut)
                .lt(OrderOutputDo::getUpdateTime, dateBefore)
                .gt(OrderOutputDo::getUpdateTime, dateSevenBefore);
        if ("0".equals(type)) {
            hasSendOutWrapper.last("limit 50");
        }
        List<OrderOutputDo> hasCheckDos = orderOutputDao.selectList(hasCheckWrapper);
        List<OrderOutputDo> hasSendDos = orderOutputDao.selectList(hasSendOutWrapper);

        List<OrderOutNotificationListRes> hasCheckList = handlerOrderOutList(hasCheckDos, 1);
        List<OrderOutNotificationListRes> hasSendOutList = handlerOrderOutList(hasSendDos, 2);

        result.put("hasCheckList", hasCheckList);
        result.put("hasSendOutList", hasSendOutList);

        return SingleResult.success(result);
    }

    private List<OrderOutNotificationListRes> handlerOrderOutList(List<OrderOutputDo> orderOutputDos, int type) {
        List<OrderOutNotificationListRes> resList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(orderOutputDos)) {
            orderOutputDos.forEach(orderOutputDo -> {
                OrderOutNotificationListRes res = new OrderOutNotificationListRes();
                res.setOrderNumber(orderOutputDo.getOrderOutputNumber());
                res.setTrackNumber(orderOutputDo.getTrackNumber());
                res.setSku(orderOutputDo.getCommoditySku() + "/" + orderOutputDo.getStorageSku());

                DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(orderOutputDo.getTrackId());
                if (businessItemDo != null) {
                    res.setTrackName(businessItemDo.getDicItemValue());
                }

                businessItemDo = dicBusinessItemDao.selectById(orderOutputDo.getStatus());
                if (businessItemDo != null) {
                    res.setStatus(businessItemDo.getDicItemValue());
                }

                if (1==orderOutputDo.getShipmentType()){
                    res.setOrderType("SHIPMENT_TYPE_1");//次日达
                }else {
                    res.setOrderType("SHIPMENT_TYPE_0");//普通
                }
                CompanyDo companyDo = companyDao.selectById(orderOutputDo.getCompanyId());
                if (companyDo != null) {
                    res.setCompanyCode(companyDo.getCompanyCode());
                }
                StorageDo storageDo = storageDao.selectById(orderOutputDo.getStorageId());
                if (storageDo != null) {
                    res.setStorage(storageDo.getCode());
                }

                if (type == 1) {
                    res.setDays(DateFormater.formatConDay(orderOutputDo.getCreateTime()));
                } else if (type == 2) {
                    res.setDays(DateFormater.formatConDay(orderOutputDo.getUpdateTime()));
                }
                resList.add(res);

            });
        }
        return resList;
    }


    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<NotificationDo> wrapper = queryBuild(map);
        IPage<NotificationDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<NotificationPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<NotificationPageRes> handlerListAfter(List<NotificationDo> list) {
        List<NotificationPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(notificationDo -> {
                NotificationPageRes res = new NotificationPageRes();
                res.setId(notificationDo.getId());
                res.setContent(notificationDo.getContent());
                res.setCreateTime(notificationDo.getCreateTime());
                res.setTitle(notificationDo.getTitle());
                result.add(res);
            });
        }
        return result;
    }

    private IPage<NotificationDo> pageInit(Map<String, String> map) {
        IPage<NotificationDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<NotificationDo> queryBuild(Map<String, String> map) {
        QueryWrapper<NotificationDo> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        return wrapper;
    }


}
